public class Solution9 {
    //123. 买卖股票的最佳时机 III
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int[][] f = new int[n][3]; // f[i][j] 表示第i天，完成j次交易后处于买入状态的最大利润
        int[][] g = new int[n][3]; // g[i][j] 表示第i天完成j次交易后处于卖出状态的最大利润
        f[0][0] = -prices[0]; g[0][0] = 0;
        for (int i = 1; i <= 2; i++) {
            f[0][i] = -0x3f3f3f3f;
            g[0][i] = -0x3f3f3f3f;
        }

        for (int i = 1; i < n; i++) {
            for (int j = 0; j < 3; j++) {
                f[i][j] = Math.max(f[i-1][j],g[i-1][j]-prices[i]);
                g[i][j] = g[i-1][j];
                if (j-1 >= 0) {
                    g[i][j] = Math.max(g[i-1][j],f[i-1][j-1]+prices[i]);
                }
            }
        }
        int ret = Math.max(g[n-1][0],g[n-1][1]);
        return Math.max(ret,g[n-1][2]);
    }
}
